package com.zbkj.crmeb.order.channel;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.crmeb.core.common.CommonResult;
import com.utils.HttpUtils;
import com.utils.RestTemplateUtil;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.*;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.BuyerOrderRequest;
import com.zbkj.crmeb.order.request.DaigoOrderRequest;
import com.zbkj.crmeb.order.response.BuyerOrderResponse;
import com.zbkj.crmeb.order.response.DaigoOrderResponse;
import com.zbkj.crmeb.store.dao.PurchaseOrderDao;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@Service("daigoStoreOrderService")
public class DaigoStoreOrderServiceImpl extends AbstractStoreOrderService {
    private static Logger logger = LoggerFactory.getLogger(DaigoStoreOrderServiceImpl.class);
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Resource
    private PurchaseOrderDao purchaseOrderDao;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    StoreOrderFactory storeOrderFactory;

    /********* daigo配置参数 *********/
    @Value("${daigo.url}")
    private String daigoUrl;
    @Value("${daigo.appkey}")
    private String daigoAppKey;
    @Value("${daigo.appsecret}")
    private String daigoAppSecret;

    /**
     * 连接超时 毫秒
     */
    private static final Integer CONNECT_TIME_OUT = 5000;
    /**
     * 响应超时 毫秒
     */
    private static final Integer RESP_TIME_OUT = 30000;

    @Override
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        DaigoOrderRequest request = new DaigoOrderRequest();
//        request.setOrderSn(storeOrder.getOrderId());
        if(9 != storeOrder.getSource()) {
            storeOrder.setPushOrderNo(orderInfoVoList.get(0).getChildOrderNumber());
        }
        request.setOrderSn(storeOrder.getPushOrderNo());
        request.setShipperName("");
        request.setShipperMobile("");
        request.setShippingType(storeOrder.getShippingType());
        List<DaigoOrderRequest.Goods> goodsList = new ArrayList<>();
        for(StoreOrderInfoVo info : orderInfoVoList){
            DaigoOrderRequest.Goods goods = new DaigoOrderRequest.Goods();
            goods.setQty(info.getInfo().getCartNum());
            String sourceSkuId = info.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
            if(sourceSkuId.startsWith(ProductTypeEnum.DAIGO.getCode()+"-")){
                sourceSkuId = sourceSkuId.replaceFirst(ProductTypeEnum.DAIGO.getCode()+"-","");
            }
            goods.setSkuId(sourceSkuId);
            goodsList.add(goods);
//            Integer tempId = info.getInfo().getProductInfo().getTempId();
            request.setConsignee(storeOrder.getRealName());
            request.setMobile(storeOrder.getUserPhone());

            if(storeOrder.getAreaType()==1){
                request.setRegion("中国");
            }else if (storeOrder.getAreaType()==3){
                request.setRegion("海外");
            }else {
                request.setRegion("");
            }
            request.setProvince(storeOrder.getProvince());
            request.setCity(storeOrder.getCity());
            request.setDistrict(storeOrder.getDistrict());
            request.setAddress(storeOrder.getDetail());

        }
        request.setGoodsList(goodsList);
        return addChannelOrder(storeOrder, request, orderInfoVoList);
        // return CommonResult.success();
    }

    @Override
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
//        BuyerOrderResponse response = null;
//        logger.info("---------------请求daigo取消订单, 订单id: {} ---------------",storeOrder.getOrderId());
//        String timestamp = String.valueOf(Instant.now().getEpochSecond());
//        String random = String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999));
//        String signature = getSignature(timestamp, random);
//        PurchaseOrderRequest request = new PurchaseOrderRequest();
//        request.setStoreOrderId(storeOrder.getOrderId());
//        PurchaseOrder purchaseOrder = purchaseOrderDao.getPurchaseOrderByOrderId(request);
//        if(null == purchaseOrder){
//            logger.info("---------------请求daigo取消订单, 采购单不存在订单id: {} ---------------",storeOrder.getOrderId());
//           return CommonResult.failed("采购单不存在！");
//        }
//        String result = null;
//        String url = buyUrl+"?appkey="+buyAppKey+"&appsecret="+daigoAppSecret+"&t="+timestamp+"&r="+random+"&s="+signature+"&op="+"order_v1"+"&action="+"cancel"+"&order_sn="+purchaseOrder.getChannelOrderSn();
//        try {
//            logger.info("--------------- 开始请求daigo取消订单url: {}---------------", url);
//            result = HttpUtils.sendGet(url,null);
//            logger.info("--------------- 请求daigo取消订单返回结果: {} ---------------", result);
//            response = JSONObject.parseObject(result,BuyerOrderResponse.class);
//            //daigo新增订单成功，创建采购单
//            if("Success".equals(response.getStatus())){
//                storeOrder.setPushStatus(ChannelPushStatusEnum.CANCEL.getCode());
//                storeOrder.setPushMessage(ChannelPushStatusEnum.CANCEL.getMsg());
//                storeOrderDao.updateById(storeOrder);
//            }
//        } catch (Exception e) {
//            logger.info("--------------- 请求daigo取消单失败结果: {} ---------------", e);
//        }
//        return CommonResult.failed(response.getMessage());

        return  null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        DaigoOrderResponse response = null;
        logger.info("---------------请求daigo查询订单, 订单sn: {} ---------------",channelOrderSn);
        String timestamp = String.valueOf(Instant.now().getEpochSecond());
        String random = String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999));
        String signature = getSignature(timestamp, random);
        String result = null;
        String url = daigoUrl +"?appkey="+daigoAppKey+"&appsecret="+daigoAppSecret+"&t="+timestamp+"&r="+random+"&s="+signature+"&op="+"order_v1"+"&action="+"info"
                +"&order_sn="+channelOrderSn;
        try {
            logger.info("--------------- 开始请求daigo创建订单url: {} ---------------", url );
            result = HttpUtils.sendGet(url, null);
            logger.info("--------------- 请求daigo创建订单返回结果: {} ---------------", result);
            response = JSONObject.parseObject(result, DaigoOrderResponse.class);

            if("Success".equals(response.getStatus())){

                return CommonResult.success(response.getOrder(),"查询成功");
            }else
            {
                return  CommonResult.failed(response.getMessage());
            }


        } catch (Exception e) {
            logger.info("--------------- 请求daigo创建订单失败结果: {} ---------------", e);
        }

        return null;
    }


    /**
     * 获取daigo商品数据和详情
     * @Description:
     * @author daigb
     * @param @param id 商品barCode
     * @param @return
     * @param @throws Exception
     * @return BuyerProductResDTO
     * @throws
     */
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder, DaigoOrderRequest request, List<StoreOrderInfoVo> orderInfoVoList) {
        DaigoOrderResponse response = null;
        logger.info("---------------请求daigo创建订单, 商品id: {} ---------------");
        String timestamp = String.valueOf(Instant.now().getEpochSecond());
        String random = String.valueOf(ThreadLocalRandom.current().nextInt(1000, 9999));

        String signature = getSignature(timestamp, random);
        String result = null;
        String url = daigoUrl +"?appkey="+daigoAppKey+"&appsecret="+daigoAppSecret+"&t="+timestamp+"&r="+random+"&s="+signature+"&op="+"order_v1"+"&action="+"add";
        try {
            logger.info("--------------- 开始请求daigo创建订单url: {},body:{} ---------------", url , JSONObject.toJSONString(request));
            result = HttpUtils.post(url, JSONObject.toJSONString(request), RESP_TIME_OUT,CONNECT_TIME_OUT);
            logger.info("--------------- 请求daigo创建订单返回结果: {} ---------------", result);
            response = JSONObject.parseObject(result, DaigoOrderResponse.class);
            //daigo新增订单成功，创建采购单
            if("Success".equals(response.getStatus())){
                // 成功
//                if(storeOrder.getPushStatus() != 2){

                    String order_sn = response.getOrder().getChannelOrderSn();

                	//新增采购单
                	storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.DAIGO.getCode());
                	//新增采购商品
                	storeOrderFactory.insertPurchaseGoods(orderInfoVoList, storeOrder, true, "万象推送: 成功", order_sn, false);
        			StoreOrder storeOrderUpdate = new StoreOrder();
        			storeOrderUpdate.setId(storeOrder.getId());
        			storeOrderUpdate.setPushStatus(1);
        			storeOrderUpdate.setPushMessage("万象推送成功！");
                    storeOrderDao.updateById(storeOrderUpdate);
                    return CommonResult.success();
//                }
            }
        } catch (Exception e) {
            logger.info("--------------- 请求daigo创建订单失败结果: {} ---------------", e);
        }

        // 失败
        storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.DAIGO.getCode());
        storeOrderFactory.insertPurchaseGoods(orderInfoVoList, storeOrder, false, response.getMessage(), null, false);
		StoreOrder storeOrderUpdate = new StoreOrder();
		storeOrderUpdate.setId(storeOrder.getId());
		storeOrderUpdate.setPushStatus(2);
		storeOrderUpdate.setPushMessage("万象推送失败:"+response.getMessage());
        storeOrderDao.updateById(storeOrderUpdate);
        return CommonResult.failed(response.getMessage());
    }

    // 签名
    private String getSignature(String timestamp, String random) {
        Map<String, String> signMap = MapUtil.newHashMap(4);
        signMap.put("timeStamp", timestamp);
        signMap.put("randomStr", random);
        signMap.put("appkey", this.daigoAppKey);
        signMap.put("appsecret", this.daigoAppSecret);

        List<String> valueList = signMap.entrySet().stream().sorted(Map.Entry.comparingByValue()).map(Map.Entry::getValue).collect(Collectors.toList());
        String signStr = StringUtils.join(valueList, null);
        signStr = DigestUtil.sha1Hex(signStr);
        signStr = DigestUtil.md5Hex(signStr);
        signStr = DigestUtil.md5Hex(signStr);

        return signStr.toUpperCase();

    }

//    private void setAddress(StoreOrder storeOrder,Integer tempId, DaigoOrderRequest request){
//        //发货地大陆
//       // if(StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.CN)){
//            request.setConsignee(storeOrder.getRealName());
//            request.setMobile(storeOrder.getUserPhone());
//            request.setRegion(AreaTypeEnum.getTypeByCode(storeOrder.getAreaType()).getTypeName());
//            request.setProvince(storeOrder.getProvince());
//            request.setCity(storeOrder.getCity());
//            request.setDistrict(storeOrder.getDistrict());
//            request.setAddress(storeOrder.getDetail());
////        }else {
////            ChannelMerchant merchant = channelMerchantService.getById(storeOrder.getMerId());
////            if(!Objects.isNull(merchant)){
////                String detail = merchant.getDetail();
////                String[] addr = StringUtils.isNotBlank(detail) ? detail.split("\\s+") : new String[1];
////                if(5 == addr.length ){
////                    request.setRegion(addr[0]);
////                    request.setProvince(addr[1]);
////                    request.setCity(addr[2]);
////                    request.setDistrict(addr[3]);
////                    request.setAddress(addr[4]);
////                }
////                request.setConsignee(merchant.getConsigneeName());
////                request.setMobile(merchant.getConsigneePhone());
////            }
////        }
//    }

}
